# @Time : 2024-11-05 13:50
# @Author : Fioman 
# @Phone : 13149920693
"""
Condition实现协同工作,比如使用两个线程进行对话.
"""
import threading


class AskThread(threading.Thread):
    def __init__(self, name, conditaion: threading.Condition):
        super(AskThread, self).__init__()
        self.name = name
        self.condition = conditaion

    def run(self):
        with self.condition:
            print("你的名字叫什么?")
            self.condition.notify()
            self.condition.wait()
            print("你的年龄是多少?")
            self.condition.notify()
            self.condition.wait()


class AnswerThread(threading.Thread):
    def __init__(self, name, conditaion: threading.Condition):
        super(AnswerThread, self).__init__()
        self.name = name
        self.condition = conditaion

    def run(self):
        with self.condition:
            self.condition.wait()
            print("我的名字是Fioman")
            self.condition.notify()
            self.condition.wait()
            print("我的年龄是30岁")


if __name__ == '__main__':
    condition = threading.Condition()
    askThread = AskThread("askThread", condition)
    answerThread = AnswerThread("answerThread", condition)
    answerThread.start()  # 注意必须是那个等待通知的线程先开启,不然如果是通知的线程先开启的
    # 等待通知的那个线程开启的时候就会错过通知,错过通知之后,就接收不到通知了,就会一直阻塞到那里
    askThread.start()

    answerThread.join()
    askThread.join()
